﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace WXWorkSvc.Common.Models;

public class RoleItem
{
    /// <summary>
    /// Flag，2的n次方
    /// </summary>
    public int Key { get; set; }
    public string Name { get; set; } = default!;
    public bool Value { get; set; }
    public RoleItem() { }
    public RoleItem(int id, string roleName, bool isRole)
    {
        Key = id;
        Name = roleName;
        Value = isRole;
    }
}

public interface IRole
{
    Type EnumType { get; }
    int Admin { get; }

    List<RoleItem> GetRoleItems(int roles)
    {
        List<RoleItem> items = new();

        foreach (var e in Enum.GetValues(EnumType))
        {
            var id = (int)e;
            var name = e.ToString();
            var isRole = (id & roles) > 0;
            items.Add(new RoleItem(id, name!, isRole));
        }
        return items;
    }
    string GetRoleNames(int roles)
    {
        List<string> items = new();

        foreach (var e in Enum.GetValues(EnumType))
        {
            if ((((int)e) & roles) > 0)
                items.Add(e.ToString()!);
        }
        return string.Join('|', items);
    }
    int GetRoles(List<RoleItem> roleItems)
    {
        return roleItems.Where(ii => ii.Value).Sum(ii => ii.Key);
    }
    List<Claim> GetRoleClaims(int roles)
    {
        List<Claim> items = new List<Claim>();
        foreach (var e in Enum.GetValues(EnumType))
        {
            var id = (int)e;
            if ((id & roles) > 0)
                items.Add(new Claim(ClaimTypes.Role, e.ToString()!));

        }
        return items;
    }

}


public class RoleBase<T> : IRole where T : struct, Enum
{
    public RoleBase()
    {
        var type = typeof(T);
        if (type.GetCustomAttribute<FlagsAttribute>() == null)
            throw new Exception("枚举必须有Flag特性");
        var adminField = type.GetField("管理员");
        if (adminField == null)
            throw new Exception("必须有“管理员”的角色");
        var v = (int)adminField.GetValue(null)!;
        if (v != 1)
            throw new Exception("“管理员”的值必须是1");

        EnumType = type;
        Admin = (int)adminField.GetValue(null)!;
    }
    public Type EnumType { get; }
    public int Admin { get; }
}
